#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from web.form.wiki import WikiModuleForm
from web import models
from utils.encrypt import uid
from utils.tencent.cos import upload_to_bucket


def wiki(request, project_id):

    wiki_id = request.GET.get('wiki_id')
    if wiki_id:
        if wiki_id.isdecimal():
            wiki_obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
            return render(request, 'wiki.html', {'wiki_obj': wiki_obj})

    return render(request, 'wiki.html')


def wiki_add(request, project_id):
    """ 添加wiki """

    if request.method == "GET":
        form = WikiModuleForm(request)
        # print('form', form)

        return render(request, 'wiki_form.html', {'form': form})

    if request.method == "POST":
        form = WikiModuleForm(request, data=request.POST)

        if form.is_valid():
            # 判断深度, 用户是否选择父文章
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            else:
                form.instance.depth = 1
            form.instance.project = request.tracer.project
            form.save()
            url = reverse('wiki', kwargs={'project_id': project_id})
            return redirect(url)

        return render(request, 'wiki_form.html', {'form': form})


def catalog(request, project_id):
    """ 获取wiki 目录"""

    # 从数据库中获取的数据是QuerySet类型，不能序列化
    # data = models.Wiki.objects.filter(project=request.tracer.project).values_list("id", "title", "parent") # 返回列表
    # data = models.Wiki.objects.filter(project=request.tracer.project).values("id", "title", "parent") # 返回字典
    data = models.Wiki.objects.filter(project=request.tracer.project).values("id", "title", "parent").order_by('depth', 'id')
    # print(data, type(data))
    return JsonResponse({'status': True, 'data': list(data)})


def delete(request, project_id, wiki_id):
    """ 删除文章 """
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    # 返回页面
    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)


def edit(request, project_id, wiki_id):
    """ 编辑文章 """
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_obj:
        # 返回页面
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    if request.method == "GET":
        form = WikiModuleForm(request, instance=wiki_obj)
        return render(request, 'wiki_form.html', {'form': form})

    if request.method == "POST":
        form = WikiModuleForm(request, data=request.POST, instance=wiki_obj)

        if form.is_valid():
            # 判断深度, 用户是否选择父文章
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            else:
                form.instance.depth = 1
            form.save()
            url = reverse('wiki', kwargs={'project_id': project_id})
            preview_url = f"{url}?wiki_id={wiki_id}"
            return redirect(preview_url)

        return render(request, 'wiki_form.html', {'form': form})

# 免除csrf认证
@csrf_exempt
def upload(request, project_id):
    """ wiki md 上传图片 """
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    img_obj = request.FILES.get('editormd-image-file')
    if not img_obj:
        # 文件对象不存在
        result['message'] = "文件不存在"
        return JsonResponse(result)

    bucket = request.tracer.project.bucket
    region = request.tracer.project.region
    # 获取文件扩展名
    ext = img_obj.name.rsplit('.')[-1]
    key = f"{uid(str(request.tracer.user.mobile_phone))}.{ext}"
    # 将文件对象上传到当前对象桶中
    url = upload_to_bucket(bucket, key, img_obj, region)

    result['success'] = 1
    result['url'] = url

    return JsonResponse(result)
